﻿using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Tools
{
    public partial class GoogleCalendar : Base
    {
        Tools.Helper.Google google = new Tools.Helper.Google();

        public GoogleCalendar()
        {
            InitializeComponent();
            base.SetDefaultLocation();

            DataBindTime(DateTime.Now.ToString("HH:00"));
            GetLog(DateTime.Now);
        }

        #region 其它事件

        /// <summary>
        /// 时间 格式 HH:00
        /// </summary>
        /// <param name="dateTimeStr"></param>
        public void DataBindTime(string dateTimeStr)
        {
            cob_start.DataSource = time;
            cob_start.SelectedItem = dateTimeStr;
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            GetLog(DateTime.Now);
        }

        private void btn_month_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://calendar.google.com/calendar/r/month");
        }

        private void btn_day_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://calendar.google.com/calendar/r/day");
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            GetLog(this.monthCalendar1.SelectionEnd);
        }
        #endregion

        #region  添加事件

        private void btn_add_Click(object sender, EventArgs e)//添加事件
        {
            var start = Picker_Start.Value.ToShortDateString() + " " + cob_start.Text;
            var end = Picker_End.Value.ToShortDateString() + " " + cob_end.Text;

            if (chb_all.Checked)
            {
                start = end = DateTime.Now.ToShortDateString();
            }

            Event newEvent = new Event()
            {
                Summary = txt_title.Text,
                Location = base.location,

                Start = new EventDateTime()
                {
                    DateTime = DateTime.Parse(start),
                },
                End = new EventDateTime()
                {
                    DateTime = DateTime.Parse(end),
                }
            };

            String calendarId = "primary";
            EventsResource.InsertRequest request = this.google.Service.Events.Insert(newEvent, calendarId);
            Event createdEvent = request.Execute();

            GetLog(DateTime.Now);
            txt_title.Text = "";
            MessageBox.Show("添加事件成功!");
        }
        #endregion

        #region 获取日志

        /// <summary>
        /// 获取日志
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private void GetLog(DateTime time)
        {
            //定义请求参数。
            EventsResource.ListRequest request = this.google.Service.Events.List("primary");
            request.TimeMin = Convert.ToDateTime(time.ToShortDateString());
            request.TimeMax = Convert.ToDateTime(time.AddDays(1).ToShortDateString());
            request.ShowDeleted = false;
            request.SingleEvents = true;
            //request.MaxResults = 1000;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            //列出事件。
            Events list = request.Execute();
            var events = new List<Calendar.CalenderModel>();

            if (list.Items != null && list.Items.Count > 0)
            {
                var items = list.Items.OrderBy(ex => ex.Start.DateTime).ThenBy(ex => ex.Summary);
                foreach (var item in items)
                {
                    var nr = item.Summary;
                    if (item.Start.DateTime != null)
                    {
                        events.Add(new Calendar.CalenderModel() { Title = item.Summary, Start = item.Start.DateTime.Value, End = item.End.DateTime.Value });
                    }
                }
            }

            var timeStr = DateTime.Now.ToString("HH:mm");
            var str = base.GetEevents(events, out timeStr);
            this.txt_log.Text = str;
            cob_start.SelectedItem = timeStr;
        }
        #endregion

        #region 批量添加-暂时不用

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    //obj.Add("对客户端首页调整收尾:调整服务端颜色 和客户端区分开", "沈阳市, 中国辽宁省沈阳市", "2018-07-29", "2018-07-29");
        //    //获取文件夹下所有文件

        //    var list = CommonLib.FileHelper.GetFiles(@"C:\Users\shuyu\Desktop\日报\106.华盾\1");
        //    foreach (var item in list)
        //    {
        //        var name = System.IO.Path.GetFileName(item).Replace(".pdf", "");
        //        //var nr = CommonLib.FileHelper.FileRead(item,"gb2312");
        //        var nr = getPdf(item).Replace("\r\n", "\n");
        //        var arr = Regex.Split(nr, "\n", RegexOptions.IgnoreCase);
        //        var i = 1;
        //        foreach (var temp in arr)
        //        {
        //            if (!string.IsNullOrEmpty(temp.Trim()))
        //            {
        //                var num = i.ToString();
        //                if (i < 10)
        //                {
        //                    num = "0" + i;
        //                }
        //                var _temp = num + "." + temp.Replace("2.下午", "2. 下午");
        //                google.Add(_temp, "沈阳市, 中国辽宁省沈阳市", name, name);
        //                i++;
        //            }
        //        }
        //        txt_log.Text += name + "\r\n";
        //    }
        //    MessageBox.Show("完成");
        //}

        //private string getPdf(string pdffilename)
        //{
        //    try
        //    {
        //        PdfReader pdfReader = new PdfReader(pdffilename);
        //        int numberOfPages = pdfReader.NumberOfPages;
        //        StringBuilder text = new StringBuilder();
        //        for (int i = 1; i <= numberOfPages; ++i)
        //        {
        //            text.Append(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfReader, i));
        //        }
        //        pdfReader.Close();
        //        var nr = text.ToString();
        //        return nr;
        //    }
        //    catch (Exception ex)
        //    {
        //        var nr = "原因：" + ex.ToString();
        //        return "";
        //    }
        //}
        #endregion

        #region 选择开始时间事件

        private void cob_start_SelectedIndexChanged(object sender, EventArgs e)
        {
            cob_end.SelectedItem = Convert.ToDateTime(Picker_Start.Value.ToShortDateString() + " " + cob_start.Text).AddHours(1).ToString("HH:mm");

            var flag = false;
            cob_end.Items.Clear();

            foreach (var item in time1)
            {
                if (item == cob_start.Text)
                {
                    flag = true;
                }
                if (flag)
                {
                    cob_end.Items.Add(item);
                }
            }
            cob_end.SelectedItem = Convert.ToDateTime("2018-08-16 " + cob_start.Text).AddHours(1).ToString("HH:mm");
        }
        #endregion

        #region  明日计划

        private void chb_tomorrow_CheckedChanged(object sender, EventArgs e)
        {
            if (chb_tomorrow.Checked)
            {
                txt_title.Text = "1.计划\r\n2.计划\r\n3.计划";
                cob_start.Text = "17:30";
                cob_end.Text = "17:30";
            }
            else
            {
                txt_log.Text = "";
            }
        }
        #endregion
    }
}
